package com.zgc.view.cell;

import com.fx.spring.util.SpringContextUtil;
import com.jfoenix.controls.JFXListCell;
import com.zgc.cache.ConnectionInfoCache;
import com.zgc.cache.ZkServiceCache;
import com.zgc.view.common.AlertCtrl;
import com.zgc.view.controller.ConnectListViewCtrl;
import com.zgc.view.controller.NewConnectionCtrl;
import com.zgc.zkinfo.ZkConnectionInfo;
import com.zgc.zkinfo.ZkService;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import org.springframework.util.StringUtils;

public class ConnectListViewCell extends JFXListCell<ZkConnectionInfo> {

    private final ConnectListViewCtrl connectListViewCtrl;

    private final AlertCtrl alertCtrl = SpringContextUtil.getBean(AlertCtrl.class);
    private final NewConnectionCtrl connectionCtrl = SpringContextUtil.getBean(NewConnectionCtrl.class);

    public ConnectListViewCell(ConnectListViewCtrl connectListViewCtrl) {
        this.connectListViewCtrl = connectListViewCtrl;
    }


    @Override
    protected void updateItem(ZkConnectionInfo item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null) {
            setText(null);
            setGraphic(null);
        } else {
            setGraphic(item.getStatIcon());
            setGraphicTextGap(10);
            setContextMenu(initConnectContextMenu(item));
            setText(StringUtils.isEmpty(item.getName()) ? item.getHost() : item.getName());
        }
    }

    private ContextMenu initConnectContextMenu(ZkConnectionInfo connectClient) {
        // 连接菜单
        MenuItem openConnectMenu = new MenuItem("连接");
        MenuItem editConnectMenu = new MenuItem("编辑连接");
        MenuItem closeConnectMenu = new MenuItem("关闭连接");
        MenuItem deleteConnectMenu = new MenuItem("删除连接");
        MenuItem exportCurrentConnect = new MenuItem("导出连接");

        openConnectMenu.setOnAction(event -> connectListViewCtrl.connect(connectClient));
        editConnectMenu.setOnAction(event -> connectionCtrl.showEditConnectionAlert(connectClient));
        closeConnectMenu.setOnAction(event -> {
            ZkService zkService = ZkServiceCache.getService(connectClient.getId());
            if (zkService != null) {
                zkService.cancel();
            }
        });
        deleteConnectMenu.setOnAction(event -> ConnectionInfoCache.removeConnectInfo(connectClient));
        exportCurrentConnect.setOnAction(event -> alertCtrl.setMessageAndShow(connectClient.getName() + "\n导出当前连接（待开发）"));

        return new ContextMenu(openConnectMenu, editConnectMenu, closeConnectMenu, deleteConnectMenu, exportCurrentConnect);
    }
}
